import { All, Body, Controller, Inject, Param, NotFoundException, Req } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { Request } from 'express';
import { MicroserviceGatewayService } from './microservice-gateway.service';

@Controller('api/:route(*)')
export class MicroserviceGatewayController {
  private clients: Map<string, ClientProxy> = new Map();

  constructor(
    private gatewayService: MicroserviceGatewayService,
    @Inject() private clientProxies: ClientProxy[],
  ) {
    // 初始化客户端代理映射
    this.clientProxies.forEach(client => {
      const name = Reflect.getMetadata('name', client);
      if (name) {
        this.clients.set(name, client);
      }
    });
  }

  @All()
  processRequest(
    @Param('route') route: string,
    @Body() body: any,
    @Req() req: Request,
  ): Observable<any> {
    // 根据路由获取服务名
    const serviceName = this.gatewayService.getServiceNameByRoute(route);
    if (!serviceName) {
      throw new NotFoundException(`未找到路由 ${route} 对应的服务`);
    }

    // 获取客户端代理
    const client = this.clients.get(serviceName);
    if (!client) {
      throw new NotFoundException(`服务 ${serviceName} 未找到`);
    }

    // 获取不带前缀的路径作为命令
    const path = this.gatewayService.getPathWithoutPrefix(route);

    // 发送请求到微服务
    return client.send(
      { cmd: path, method: req.method },
      { body, query: req.query, params: req.params }
    );
  }
}